package LC;

/**
 * https://leetcode.com/problems/reverse-linked-list/description/
 * Reverse a singly linked list.
 */
public class LC_206_ReverseLinkedList_LinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        ListNode h1 = Solution.reverseList(head);
        ListNode cur = h1;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode fakeNode = new ListNode(-1);
            fakeNode.next = head;
            ListNode cur = head.next;
            head.next = null;
            while (cur != null) {
                ListNode nextcur = cur.next;
                cur.next = fakeNode.next;
                fakeNode.next = cur;
                cur = nextcur;
            }
            return fakeNode.next;
        }
    }
}